 /**
 * DISCLIMER: 
 * this library is an opensource, feel free to edit or redistribute it
 * but use it with you own risk
 * 
 * ktutnik
 */
package org.ticlib.mock
{
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	
	import mx.rpc.AbstractOperation;
	import mx.rpc.AsyncToken;
	import mx.rpc.Fault;
	import mx.rpc.IResponder;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;

	public class MockOperation extends AbstractOperation
	{
		private var result:Object;
		private var fault:Object;
		private var successChance:Number;
		private var delay:Number;
		
		private var timer:Timer;
		
		private var returnObject:Object;
		private var args:Object;
		private var token:AsyncToken;
		
		final public function MockOperation(result:Object, fault:Object, successChance:Number = 1, delay:Number=2000)
		{
			this.result = result;
			this.fault = fault;
			this.successChance = successChance;
			this.delay = delay;
		}
		
		override public function send(... args):AsyncToken
		{
			timer = new Timer(delay);
			timer.addEventListener(TimerEvent.TIMER, onTimer);
			token = new AsyncToken(null);
			this.args = args;			
			timer.start();
			return token
		}
		
		private function onTimer(e:TimerEvent):void
		{
			timer.removeEventListener(TimerEvent.TIMER, onTimer);
			
			for each(var resp:IResponder in token.responders)
			{
				var rand:Number = Math.random();
				if(rand <= successChance)
				{
					if(result is Function)
						returnObject = result.apply(this, args);
					else 
						returnObject = result;
					resp.result(ResultEvent.createEvent(returnObject));
				}
				else
				{
					if(fault is Function)
						returnObject = fault.apply(this, args);
					else
						returnObject = result;
					resp.fault(FaultEvent.createEvent(new Fault("", returnObject.toString())));
				}
			
			}
		}
		
		override public function cancel(id:String=null):AsyncToken
		{
			if(!timer) return null;
			timer.stop();
			timer.removeEventListener(TimerEvent.TIMER, onTimer);
			return new AsyncToken(null);
		}
	}
}